package com.wangsh.train.web.head.controller;

import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.wangsh.train.cla.pojo.AClass;
import com.wangsh.train.cla.pojo.AClassEnum;
import com.wangsh.train.cla.service.IClassDbService;
import com.wangsh.train.common.controller.BaseController;
import com.wangsh.train.common.pojo.ApiResponse;
import com.wangsh.train.common.pojo.ApiResponseEnum;
import com.wangsh.train.common.util.ConstatFinalUtil;
import com.wangsh.train.common.util.PageInfoUtil;
import com.wangsh.train.outer.IClientOuterService;
import com.wangsh.train.system.pojo.ASysFileEnum;
import com.wangsh.train.system.pojo.ASysPro;
import com.wangsh.train.users.pojo.AUsers;
import com.wangsh.train.users.pojo.AUsersCate;
import com.wangsh.train.users.pojo.AUsersClass;
import com.wangsh.train.users.service.IUsersDbService;

/**
 * 	管理员首页操作
 * 	@author wangsh
 */
@Controller
@RequestMapping("/head/users/")
public class UsersHeadController extends BaseController
{
	@Resource
	private IUsersDbService usersDbService;
	@Resource
	private IClassDbService classDbService;
	@Resource
	private IClientOuterService clientOuterService;
	
	/**
	 * 用户列表页面
	 * @return
	 */
	@RequestMapping("/main")
	public String main(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--main--");
		return "/head/users/main";
	}
	
	/**
	 * 用户列表页面
	 * @return
	 */
	@RequestMapping("/usersList")
	public String usersList(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersList--");
		ApiResponse<AUsers> response = new ApiResponse<AUsers>();
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		String classId = request.getParameter("classId");
		if(classId == null)
		{
			classId = "" ;
		}
		request.setAttribute("classId", classId);
		if(!"".equalsIgnoreCase(classId))
		{
			/* 搜索条件,生成公共的搜索条件 */
			Map<String, Object> condMap = this.proccedSearch(request);
			condMap.put("classId", classId);
			/* 查询数据库
			 * 所有的数据以JSON的形式返回
			 *  */
			response = this.usersDbService.findCondListUsersService(pageInfoUtil, condMap);
			response.clearInfo();
		}
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		return "/head/users/usersList";
	}
	
	/**
	 * 打开用户更新页面
	 * @return
	 */
	@RequestMapping("/usersUpdate")
	public String usersUpdate(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersUpdate--");
		/* 准备请求的信息 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 从session中获取信息 */
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		String id = users.getId() + ""; 
		
		/* 接收班级Id */
		String classId = request.getParameter("classId");
		if(classId == null)
		{
			classId = "" ;
		}
		if(!"".equalsIgnoreCase(classId))
		{
			id = request.getParameter("id");
			/* 查询一下,学生id是否在此班级里面 */
			condMap.clear();
			condMap.put("classId", classId);
			condMap.put("usersId", id);
			ApiResponse<AUsersClass> usersClassResp = this.usersDbService.findOneUsersClassService(condMap);
			AUsersClass usersClass = usersClassResp.getDataOneJava();
			if(usersClass == null)
			{
				/* 查询不到学生,无法查看信息 */
				infoResponse.setCode(ApiResponseEnum.INFO_AUTH_NO.getStatus());
				infoResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(infoResponse.getCode() + ""), Collections.EMPTY_MAP);
				model.addAttribute("response", infoResponse.toJSON());
				return "forward:/common/info.htm";
			}
		}
		
		condMap.clear();
		condMap.put("id", id);
		ApiResponse<AUsers> apiResponse = this.usersDbService.findOneUsersService(condMap);
		users = apiResponse.getDataOneJava() ; 
		model.addAttribute("usersResponse", apiResponse.toJSON());
		
		/* 查询所有启用的班级 */
		condMap.clear();
		condMap.put("status", AClassEnum.STATUS_ENABLE.getStatus());
		ApiResponse<AClass> classResponse = this.classDbService.findCondListClassService(null, condMap);
		model.addAttribute("classResponse", classResponse.toJSON());
		
		String operType = request.getParameter("operType");
		if("updateInfo".equalsIgnoreCase(operType))
		{
			/* 根据不同的请求跳转不同的页面 */
			return "/head/users/usersUpdateInfo";
		}
		return "/head/users/usersInfo";
	}
	
	/**
	 * 打开用户更新页面
	 * @return
	 */
	@RequestMapping("/usersUpdateSubmit")
	public String usersUpdateSubmit(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersUpdateSubmit--");
		HttpSession session = request.getSession() ; 
		/* 从session中获取信息 */
		AUsers usersSess = (AUsers) this.findObjfromSession(request, "users");
		/* 准备请求的信息 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", usersSess.getId() + "");
		ApiResponse<AUsers> apiResponse = this.usersDbService.findOneUsersService(condMap);
		AUsers users = apiResponse.getDataOneJava() ; 
		model.addAttribute("response", apiResponse.toJSON());
		
		boolean flag = false ; 
		String operType = request.getParameter("operType");
		if("updateInfo".equalsIgnoreCase(operType))
		{
			/* 根据不同的请求跳转不同的页面 */
			/*
			 * String classId = request.getParameter("classId");
			 * users.setClassId(Integer.valueOf(classId));
			 */
			users.setUpdateTime(new Date());
			flag = true;
		}else if("updateSyna".equalsIgnoreCase(operType))
		{
			/* 同步数据 */
			JSONObject dataReqJSON = new JSONObject();
			dataReqJSON.put("token", usersSess.getTokenStr());
			/* 请求用户中心 */
			JSONObject responseJSON = this.clientOuterService.verifyUsersTokenService(dataReqJSON);
			
			if(responseJSON != null && responseJSON.getInteger("code") == ApiResponseEnum.STATUS_SUCCESS.getStatus())
			{
				//登陆成功
				JSONObject dataJSON = (JSONObject) responseJSON.get("data");
				JSONObject usersJSON = dataJSON.getJSONObject("users");
				String id = usersJSON.get("id") + "";
				String email = usersJSON.get("email") + "";
				String nickName = "";
				String trueName = "";
				String lastLoginTime = usersJSON.get("lastLoginTime") + "";
				/* 判断字符串 */
				if(usersJSON.get("nickName") != null)
				{
					nickName = usersJSON.get("nickName") + "" ;
				}
				if(usersJSON.get("trueName") != null)
				{
					trueName = usersJSON.get("trueName") + "" ;
				}
				
				users.setEmail(email);
				users.setNickName(nickName);
				users.setTrueName(trueName);
				users.setSsoId(Integer.valueOf(id));
				users.setUpdateTime(new Date());
				users.setLastLoginTime(this.dateFormatUtil.strDateTime(lastLoginTime));
				users.setUpdateTime(new Date());
				flag = true;
			}
		}
		
		ApiResponse<Object> dbResponse = new ApiResponse<Object>();
		if(flag)
		{
			dbResponse = this.usersDbService.updateOneUsersService(users);
			session.setAttribute("users", users);
		}
		/* 存储结果 */
		model.addAttribute("response", dbResponse.toJSON());
		return this.usersUpdate(request, model);
	}
	
	/**
	 * 用户班级列表页面
	 * @return
	 */
	@RequestMapping("/usersClassList")
	public String usersClassList(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersClassList--");
		/* 从session中获取信息 */
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		String classType = request.getParameter("classType");
		String defType = request.getParameter("defType");
		request.setAttribute("classType", classType);
		request.setAttribute("defType", defType);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		condMap.put("classType",classType);
		condMap.put("usersId", users.getId());
		condMap.put("defType", defType);
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		ApiResponse<AUsersClass> response = this.usersDbService.findCondListUsersClassService(pageInfoUtil, condMap);
		response.clearInfo();
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		return "/head/users/usersClassList";
	}
	
	/**
	 * 用户分类列表页面
	 * @return
	 */
	@RequestMapping("/usersCateList")
	public String usersCateList(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersCateList--");
		/* 接收参数 */
		String cateTempId = request.getParameter("cateTempId");
		if(cateTempId == null)
		{
			cateTempId = ""; 
		}
		request.setAttribute("cateTempId", cateTempId);
		
		/* 只能查询自己的用户分类 */
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		/* 查询用户指定的班级 */
		condMap.put("usersClaId", users.getUsersClassId());
		condMap.put("cateTempId", cateTempId);
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		ApiResponse<AUsersCate> response = this.usersDbService.findCondListUsersCateService(pageInfoUtil, condMap);
		response.clearInfo();
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		return "/head/users/usersCateList";
	}
	
	/**
	 * 打开添加用户分类页面
	 * @return
	 */
	@RequestMapping("/usersCateInsert")
	public String usersCateInsert()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersCateInsert--");
		return "/head/users/usersCateInsert";
	}
	
	/**
	 * 添加用户分类提交操作
	 * @return
	 */
	@RequestMapping(value = "/usersCateInsertSubmit")
	public String usersCateInsertSubmit(String pubTimeStr , String currDateStr , AUsersCate usersCate,
			HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersCateInsertSubmit--");
		/* 保存结果 */
		ApiResponse dbResponse = new ApiResponse<Object>();
		/* 只能查询自己的用户分类 */
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		
		try
		{
			ASysPro stuDaySys = (ASysPro) ConstatFinalUtil.SYS_PRO_MAP.get("usersCate_template_id_stuDay");
			ASysPro stuWeekSys = (ASysPro) ConstatFinalUtil.SYS_PRO_MAP.get("usersCate_template_id_week");
			ASysPro stuMonthSys = (ASysPro) ConstatFinalUtil.SYS_PRO_MAP.get("usersCate_template_id_month");
			if(usersCate.getCateTempId() == Integer.valueOf(stuDaySys.getVals()))
			{
				usersCate.setCurrDate(this.dateFormatUtil.strDate(currDateStr));
			}else if(usersCate.getCateTempId() == Integer.valueOf(stuWeekSys.getVals()))
			{
				usersCate.setCurrDate(this.dateFormatUtil.strDate(currDateStr));
			}else if(usersCate.getCateTempId() == Integer.valueOf(stuMonthSys.getVals()))
			{
				usersCate.setCurrDate(this.dateFormatUtil.strDate(currDateStr,"yyyy-MM")); 
			}
			
			usersCate.setUsersClaId(users.getUsersClassId());
			/* 为对象赋值 */
			usersCate.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
			usersCate.setUpdateTime(new Date());
			dbResponse = this.usersDbService.saveOneUsersCateService(usersCate);
			ConstatFinalUtil.SYS_LOGGER.info("--用户分类添加返回结果:{}--",dbResponse.toJSON());
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("添加一条记录失败了",e);
			dbResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			dbResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(dbResponse.getCode() + "") , infoMap);
		}
		model.addAttribute("response", dbResponse.toJSON());
		return this.usersCateInsert();
	}
	
	/**
	 * 打开更新用户分类页面
	 * @return
	 */
	@RequestMapping("/usersCateUpdate")
	public String usersCateUpdate(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersCateUpdate--");
		String id = request.getParameter("id");
		String operType = request.getParameter("operType");
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		/* 查询数据库 */
		ApiResponse<AUsersCate> response = this.usersDbService.findOneUsersCateService(condMap);
		AUsersCate usersCate = response.getDataOneJava() ;
		response.clearInfo();
		/* 存储request */
		model.addAttribute("response", response.toJSON());
		
		if("update".equalsIgnoreCase(operType))
		{
			return "/head/users/usersCateUpdate";
		}else if("file".equalsIgnoreCase(operType))
		{
			/* 上传文件 */
			model.addAttribute("name", "上传用户分类");
			model.addAttribute("recName", "");
			
			model.addAttribute("operType", "insert");
			model.addAttribute("relaId", id);
			model.addAttribute("fileType", ASysFileEnum.FILETYPE_COMMON.getStatus());
			model.addAttribute("fileRelaType", ASysFileEnum.FILERELATYPE_USERSCATE.getStatus());
			model.addAttribute("url", "/head/system/sysFileFileUpdateSubmit.htm?relaId=" + id);
			return "/head/system/sysFileFileUpdate";
		}
		return "/head/users/usersCateInfo";
	}
	
	/**
	 * 更新用户分类提交操作
	 * @return
	 */
	@RequestMapping(value = "/usersCateUpdateSubmit")
	public String usersCateUpdateSubmit(String id,
			HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersCateUpdateSubmit--");
		/* 返回关系 */
		ApiResponse dbResponse = new ApiResponse<Object>();
		/* 只能查询自己的用户分类 */
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		try
		{
			/* 准备查询条件 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", id);
			/* 查询数据库 */
			ApiResponse<AUsersCate> response = this.usersDbService.findOneUsersCateService(condMap);
			/* 获取java对象 */
			AUsersCate usersCate = response.getDataOneJava() ;
			
			Map<String, Object> paramsMap = new HashMap<String,Object>();
			boolean flag = false ; 
			String operType = request.getParameter("operType");
			if("update".equalsIgnoreCase(operType))
			{
				/* 接收参数 */
				String status = request.getParameter("status");
				String pubTimeStr = request.getParameter("pubTimeStr");
				String currDateStr = request.getParameter("currDateStr");
				String content = request.getParameter("content");
				/* 设置属性 */
				usersCate.setContent(content);
				usersCate.setStatus(Byte.valueOf(status));
				usersCate.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
				
				ASysPro stuDaySys = (ASysPro) ConstatFinalUtil.SYS_PRO_MAP.get("usersCate_template_id_stuDay");
				ASysPro stuWeekSys = (ASysPro) ConstatFinalUtil.SYS_PRO_MAP.get("usersCate_template_id_week");
				ASysPro stuMonthSys = (ASysPro) ConstatFinalUtil.SYS_PRO_MAP.get("usersCate_template_id_month");
				if(usersCate.getCateTempId() == Integer.valueOf(stuDaySys.getVals()))
				{
					usersCate.setCurrDate(this.dateFormatUtil.strDate(currDateStr));
				}else if(usersCate.getCateTempId() == Integer.valueOf(stuWeekSys.getVals()))
				{
					usersCate.setCurrDate(this.dateFormatUtil.strDate(currDateStr));
				}else if(usersCate.getCateTempId() == Integer.valueOf(stuMonthSys.getVals()))
				{
					usersCate.setCurrDate(this.dateFormatUtil.strDate(currDateStr,"yyyy-MM")); 
				}
				
				flag = true ; 
			}
			
			if(flag)
			{
				usersCate.setUsersClaId(users.getUsersClassId());
				
				/* 数据库操作 */
				dbResponse = usersDbService.updateOneUsersCateService(usersCate);
				ConstatFinalUtil.SYS_LOGGER.info("--用户分类添加返回结果:{}--",dbResponse.toJSON());
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("更新一条记录失败了",e);
			dbResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			dbResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(dbResponse.getCode() + "") , infoMap);
		}
		model.addAttribute("response", dbResponse.toJSON());
		return "/head/users/usersCateUpdate";
	}
	
	/**
	 * 退出页面
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response , HttpSession session)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--logout--");
		String returnUrl = request.getParameter("returnUrl");
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 获取用户 */
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		if(returnUrl == null)
		{
			returnUrl = "" ; 
		}
		try
		{
			returnUrl = URLEncoder.encode(returnUrl, "UTF-8");
			/* 做一些清除的操作 */
			session.removeAttribute("users");
			session.removeAttribute("lastLoginTime");
			
			apiResponse.setCode(ApiResponseEnum.INFO_LOGOUT.getStatus()); 
			/* 客户端跳转到登陆页面 */
			String logoutUrl = ConstatFinalUtil.CONFIG_JSON.getString("usersCenter.head.logout.url");
			logoutUrl += "&returnUrl=" + URLEncoder.encode(returnUrl,"UTF-8") ; 
			response.sendRedirect(logoutUrl);
			return null ; 
		} catch (Exception e)
		{
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus()); 
			ConstatFinalUtil.SYS_LOGGER.error("退出报错了;email:{}", users.getEmail(),e);
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		/* 提示信息 */
		session.setAttribute("response", apiResponse.toJSON());
		return null ; 
	}
}
